package com.pingan.pastry.rpc.support;

import com.google.gson.Gson;
/*import com.pingan.pastry.entity.Cat;
import com.pingan.pastry.spi.UserSPI;*/

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class MockInvoker implements InvocationHandler {

    private Class target;

    private Gson gson = new Gson();

    public MockInvoker() {
    }

    public MockInvoker(Class target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        /**
         * 1.获取文件所处路径的到文件的，并根据当前调用的方法读取正确的json
         * 2.file操作将json 读取并返回给调用端
         * 3. GSON 操作
         */
        InputStream resourceAsStream = null;
        BufferedReader reader = null;
        try {
            resourceAsStream = this.getClass().getResourceAsStream("/mock" + obtainFilePath(method));
            reader = new BufferedReader(new InputStreamReader(resourceAsStream));
            StringBuffer result = new StringBuffer();
            while (reader.read() != -1) {
                result.append(reader.readLine());
            }
            System.out.println(result.toString());
            /*Cat cat = gson.fromJson(result.toString(), Cat.class);
            System.out.println("cat: " + cat);*/
            return result.toString();
        } finally {
            if (resourceAsStream != null) {
                resourceAsStream.close();
            }
            if (reader != null) {
                reader.close();
            }
        }
    }

    private String obtainFilePath(Method method) {
        StringBuffer sb = new StringBuffer();
        sb.append("/").append(target.getSimpleName().toLowerCase());
        sb.append("/").append(method.getName().toLowerCase());
        sb.append(".json");
        return sb.toString();
    }

    public void test() {
        InputStream resourceAsStream = this.getClass().getResourceAsStream("/application11.yml");
        System.out.println(resourceAsStream);
    }


   /* public static void main(String[] args) throws Throwable {
        MockProxyHandler handler = new MockProxyHandler(UserSPI.class);
        Method[] methods = UserSPI.class.getMethods();
        Method target = null;
        for (Method method : methods) {
            if (method.getName().equals("listUser")) {
                target = method;
            }
        }
        Object invoke = handler.invoke(null, target, null);
    }*/
}
